import { getAntd,getEcCom,getLabel } from './convert';
import base from "./base";
import * as GlobalUtil from '../util/public/globalUtil';
const openFullWindowHaveBar = (url) => {
	var width = screen.availWidth - 10;
	var height = screen.availHeight - 50;
	var szFeatures = "top=0,";
	szFeatures += "left=0,";
	szFeatures += "width=" + width + ",";
	szFeatures += "height=" + height + ",";
	szFeatures += "directories=no,";
	szFeatures += "status=yes,toolbar=no,location=no,";
	szFeatures += "menubar=no,";
	szFeatures += "scrollbars=yes,";
	szFeatures += "resizable=yes";
	window.open(url, "", szFeatures);
}
window.openFullWindowHaveBar = openFullWindowHaveBar;

const openUnFullWindow = (url,width,height,top,left) => {
	var szFeatures = "top="+top+",";
	szFeatures += "left="+left+",";
	szFeatures += "width="+width+",";
	szFeatures += "height="+height+",";
	szFeatures += "directories=no,";
	szFeatures += "status=yes,toolbar=no,location=no,";
	szFeatures += "menubar=no,";
	szFeatures += "scrollbars=yes,";
	szFeatures += "resizable=yes";
	window.open(url, "", szFeatures);
}
window.openUnFullWindow = openUnFullWindow;

const openFullWindowHaveBarForWFList = (url, requestid) => {
	try {
		document.getElementById("wflist_" + requestid + "span").innerHTML = "";
	} catch (e) {}
	const redirectUrl = url;
	const width = screen.availWidth - 10;
	const height = screen.availHeight - 50;
	let szFeatures = "top=0,";
	szFeatures += "left=0,";
	szFeatures += "width=" + width + ",";
	szFeatures += "height=" + height + ",";
	szFeatures += "directories=no,";
	szFeatures += "status=yes,toolbar=no,location=no,";
	szFeatures += "menubar=no,";
	szFeatures += "scrollbars=yes,";
	szFeatures += "resizable=yes"; // channelmode
	window.open(redirectUrl, "", szFeatures);
}
window.openFullWindowHaveBarForWFList = openFullWindowHaveBarForWFList;

//图片懒加载
window.formImgLazyLoad = function(container){
	const { propFileCfg = {} } = base.layoutStore;
	const { handwriting_download_switch = "0" } = propFileCfg;
	if(!!!container || container.length === 0)
		return;
	// 获取父元素的高度
	var contHeight = container.outerHeight();
	var contWidth = container.outerWidth();
	// 获取父元素相对于文档页顶部的距离，这边要注意了，分为以下两种情况；
	if (container.get(0) === window) {
		// 第一种情况父元素为window，获取浏览器滚动条已滚动的距离；$(window)没有offset()方法；
		var contop = $(window).scrollTop();
		var conleft = $(window).scrollLeft();
	} else {
		// 第二种情况父元素为非window元素，获取它的滚动条滚动的距离；
		var contop = container.offset().top;
		var conleft = container.offset().left;
	}
	
	container.find("img[original-src]").each(function(){
		//对象顶部与文档顶部之间的距离，如果它小于父元素底部与文档顶部的距离，则说明垂直方向上已经进入可视区域了；
		//console.log("jQuery(this).offset().top--",jQuery(this).offset().top,"contop--",contop,"contHeight--",contHeight)
		var post = jQuery(this).offset().top - (contop + contHeight);
		//对象底部与文档顶部之间的距离，如果它大于父元素顶部与文档顶部的距离，则说明垂直方向上已经进入可视区域了；
		var posb = jQuery(this).offset().top + jQuery(this).height() - contop;
		// 水平方向上同理；
		var posl = jQuery(this).offset().left - (conleft + contWidth);
		var posr = jQuery(this).offset().left + jQuery(this).width() - conleft;

		//console.log("jQuery(this).is(':visible')",jQuery(this).is(':visible'),"post--",post,"posb--",posb,"posl--",posl,"posr--",posr);
		if ((post < 0 && posb > 0) && (posl < 0 && posr > 0)) {
			var originalSrc = jQuery(this).attr("original-src");
			if (originalSrc != "") {
				jQuery(this).removeAttr("src").attr("src", originalSrc).removeAttr("original-src");
				jQuery(this).removeAttr("style").attr("style", jQuery(this).attr("original-style")).removeAttr("original-style");
				jQuery(this).attr("width", jQuery(this).attr("original-width")).removeAttr("original-width");
				jQuery(this).attr("height", jQuery(this).attr("original-height")).removeAttr("original-height");
				jQuery(this).attr("onload", jQuery(this).attr("original-onload")).removeAttr("original-onload");
				jQuery(this).attr("onresize", jQuery(this).attr("original-onresize")).removeAttr("original-onresize");
				//签章图片和手写签批图片不能预览
				let handwritingPre = handwriting_download_switch == 1 && jQuery(this).attr("name") == "handWrittenSign";
				if (!jQuery(this).hasClass("signatureImg") && !handwritingPre) {//不是个性化签章和手写签批可以预览
					//绑定图片预览事件
					jQuery(this).addClass("formImgPlay");
					jQuery(this).bind("click", function () {
						window.imageCarousel(this);
					});
					
				}else{//禁止预览和拖拽
					jQuery(this).on('mousedown',function (e) {
						e.preventDefault();
					});
				}
				if(jQuery(this).hasClass("handWrittenSign")){
					GlobalUtil.handWritingHander(this);
				}
			}
		}
	});
}

//图片放大轮播
window.imageCarousel = (imgObj) =>{
    let imgPool = [];
	let indexNum = 0;
	const curImgSrc = !!jQuery(imgObj).attr("data-imgsrc") ? jQuery(imgObj).attr("data-imgsrc") : jQuery(imgObj).attr("src");
	let hasCalaulate = false;
    jQuery(".formImgPlay").each(function(){
		const imgsrc = !!jQuery(this).attr("data-imgsrc") ? jQuery(this).attr("data-imgsrc") : jQuery(this).attr("src");
		if(!!imgsrc){
			imgPool.push(imgsrc);
			if(curImgSrc === imgsrc && jQuery(imgObj).closest(".excelMainTable").length === jQuery(this).closest(".excelMainTable").length){
				hasCalaulate = true;
			}else{
				if(!hasCalaulate)
					indexNum++;
			}
		}
	});
    IMCarousel.showImgScanner4Pool(true, imgPool, indexNum, null, window.top);
}

//系统提醒工作流需要相关JS
const errorNoticeUtil = {
	handleResetBtn: function(){
		const url = jQuery('#wfSErrorResetBtn').attr('href');
		const title = jQuery('#wfSErrorResetBtn').attr('title');
		const type = jQuery('#wfSErrorResetBtn').attr('type');
		jQuery('#wfSErrorResetBtn').attr('href','javascript:void(0)').removeAttr('target').removeAttr('title');
		jQuery('#wfSErrorResetBtn').attr('onclick',"errorNoticeUtil.resetWorkflowCfg('"+url+"','"+title+"','"+type+"')");
		jQuery("#wfSErrorResetBtn").removeAttr('style');
	},
	resetWorkflowCfg: function(url,title,type){
		if(type == '3'){
			openFullWindowHaveBar(url);
			return;
		}else if(type == '1' || type == '2'){
			//url = "/workflow/request/WFReset.jsp?wfid=" + url + "&type=" + type;
			url = `/spa/workflow/static4engine/engine.html#/main/workflowengine/path/pathSet/pathDetail/flowSet/nodeInfo?needBaseTab=false&showLeftTree=false&workflowId=${url}`;
			const { WeaTools } = getEcCom();
			const dialog = WeaTools.createDialog({
                title: getLabel(33488,'流转设置'),
                moduleName: "workflow",
                url: url,
                style: {width:1020, height:600},
            });
            dialog.show();
		}
	},
	triggerSystemWorkflow: function(prefix, url, title, loginuserid, type){
		const globalStore = window.WfForm.getGlobalStore();
		const { requestid,belongTest } = globalStore.commonParam;
		if(belongTest){
			const { Modal } = getAntd();
			Modal.warning({
				title:getLabel(131329,'信息确认'),
				content: getLabel(386161,"此操作暂不支持流程测试!"),
				okText: getLabel(83446,`确定`)
			});
			return;
		}
		prefix = prefix.replace(/~0~/g, "<span class='importantInfo'>");
		prefix = prefix.replace(/~1~/g, "</span>");
		prefix = prefix.replace(/~2~/g, "<span class='importantDetailInfo'>");
		let infohtml = jQuery('.wf-error-msg-detail').html();
		if(!infohtml) {
			infohtml = "";
		} else {
			infohtml = "<div class='wf-error-msg-detail'>" + infohtml + "</div>";
		}
		const botfix = type == "3" ? getLabel(18913,"流程干预") : getLabel(126558,"进行设置");
		const messagedetail = `${infohtml}<span>${prefix}，请<a id="wfSErrorResetBtn" href="${url}" title="${title}" type="${type}"> 点击这里 </a>${botfix}</span>`;
		jQuery.ajax({
			type: 'post',
			url: '/workflow/request/TriggerRemindWorkflow.jsp?_' + new Date().getTime() + "=1",
			data: {
				remark: messagedetail,
				loginuserid: loginuserid,
				requestid: requestid
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				const { Modal } = getAntd();
				Modal.error({
					title: getLabel(131329,'信息确认'),
					content: getLabel(22397,'发送失败'),
					okText: getLabel(83446,'确定')
				});
			},
			success: function(data, textStatus) {
				const { Modal } = getAntd();
				Modal.success({
					title: getLabel(131329,'信息确认'),
					content: getLabel(516558,'已成功向提醒人发送提醒流程'),
					okText: getLabel(83446,'确定')
				});
			}
		});
	}
}
window.errorNoticeUtil = errorNoticeUtil;
//错误提示，后台设置链接
window.resetWorkflow = errorNoticeUtil.resetWorkflowCfg;

//生成系统提醒流程
window.triggerSystemWorkflow = errorNoticeUtil.triggerSystemWorkflow;

//Iframe区域相关方法
window.iframeOperate = (function(){

	function showIframeArea(vthis){
		jQuery(vthis).closest("td").find(".iframeLoading").hide();
		jQuery(vthis).show();
	}

	//Iframe区域高度自适应高度
	function autoAdjustHeight(vthis){
		var iframeObj = jQuery(vthis);
		var funObj = function(){autoAdjustHeight(vthis)};
		var eachcount = parseInt(iframeObj.attr("eachcount"));
		if(eachcount > 10){
			iframeObj.css("height", "100px");
			return;
		}
		if(window.customAutoAdjustHeight && typeof  window.customAutoAdjustHeight == "function"){
			window.customAutoAdjustHeight(vthis);
		}else{
			var contextObj = iframeObj[0].contentWindow.document;
			var bodyContentHeight = contextObj.body.scrollHeight;
			//if(window.console) console.log("scrollHeight:"+bodyContentHeight+"  |offsetHeight:"+contextObj.body.offsetHeight)
			if(bodyContentHeight == 0){
				iframeObj.attr("eachcount", eachcount+1);
				window.setTimeout(funObj, 500);
			}else{
				iframeObj.css("height", bodyContentHeight+"px");
			}
		}
	}

	return{
		//Iframe区域onload事件
		loadingOver: function(vthis){
			if(jQuery(vthis).attr("adjustheight") == "y"){
				window.setTimeout(function(){
					showIframeArea(vthis);
					autoAdjustHeight(vthis);
				},800);
			}else{
				showIframeArea(vthis);
			}
		}
	}
})();

//二维码、条形码相关方法
window.scancodeOperate = (function(){

	function adjustSize_scancode(vthis){
		try{
			var parentHeight = vthis.closest("td").height();
			var curHeight = vthis.height();
			//if(window.console)console.log("二维码/条形码宽度调整:"+parentHeight+"  |  "+curHeight);
			if(parseInt(parentHeight)-parseInt(curHeight) > 8)		//td高度会包含图片高度及上边框高度，避免死循环触发
				vthis.css("height", parentHeight);
		}catch(e){}
	}

	return {
		//ready触发自适应单元格大小（针对所在行存在高度渐变时，故绑定个resize）
		readyAdjustSize: function(obj){
			var vthis = jQuery(obj);
			vthis.resize(function(){
				adjustSize_scancode(vthis);
			});
			adjustSize_scancode(vthis);
		}
	}
})();

window.handWritingHander = (vthis) => {
	if(vthis) GlobalUtil.handWritingHander(vthis);
}
